<?php

declare(strict_types=1);

namespace Newbie\Traits;

use DI\Attribute\Inject;
use Newbie\NewbieResponse;
use support\Response;

trait ControllerTrait {
    /**
     * Newbie 响应处理
     * NewbieResponse
     */
    #[Inject]
    protected NewbieResponse $response;

    /**
     * @param string|array|object $msgOrData
     * @param array|object $data
     * @param int $code
     * @return Response
     */
    public function success (string|array|object $msgOrData = '', array|object $data = [], int $code = 200): Response {
        if (is_string($msgOrData) || is_null($msgOrData)) {
            return $this->response->success($msgOrData, $data, $code);
        } else if (is_array($msgOrData) || is_object($msgOrData)) {
            return $this->response->success(null, $msgOrData, $code);
        } else {
            return $this->response->success(null, $data, $code);
        }
    }

    /**
     * @param string $message
     * @param int $code
     * @param array $data
     * @return Response
     */
    public function error (string $message = '', int $code = 500, array $data = []): Response {
        return $this->response->error($message, $code, $data);
    }

    /**
     * 跳转
     * @param string $toUrl
     * @param int $status
     * @param array $headers
     * @return Response
     */
    public function redirect (string $toUrl, int $status = 302, $headers = []): Response {
        return redirect($toUrl, $status, $headers);
    }

    /**
     * 下载文件
     * @param string $filePath
     * @param string $name
     * @return Response
     */
    public function _download (string $filePath, string $name = ''): Response {
        return response()->download($filePath, $name)->header("Access-Control-Expose-Headers", "Content-Disposition");
    }
}